import React,{Suspense} from 'react'
import { useLocation } from 'react-router'
import {BrowserRouter,Route,Routes,Navigate} from "react-router-dom"
import {routerItem} from "../interface"
import {routes} from "./routes"
function index() {
    // 21、封装自定义HOC，实现路由拦截，考虑反向继承和属性代理的方式  11：23
    const BeforeEach=({children}:{children:JSX.Element|any})=>{
        const token=localStorage.getItem('token')
        const location=useLocation()
        if(!token&&location.pathname!=='/login'){
            return<Navigate to='/login'></Navigate>
        }
        return children
    }
    const mapRouter=(route:routerItem[])=>{
        return route.map((v,i)=>{
            return v.path?
            <Route key={i} path={v.path} element={<BeforeEach>{v.element}</BeforeEach>}>
                {
                    v.children&&mapRouter(v.children)
                }
            </Route>
            :<Route key={i} path={v.from} element={<Navigate to={v.to} />}></Route>
        })
    }
    return (
        <Suspense fallback={<h1>加载中.....</h1>}>
            <BrowserRouter>
                <Routes>
                    {
                        mapRouter(routes)
                    }
                </Routes>
            </BrowserRouter>
        </Suspense>
    )
}

export default index
